# Create your views here.
from django.shortcuts import render_to_response, get_object_or_404
from django.shortcuts import redirect
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User

from exam.models import Passage,ChooseQuestion, ChooseTwoQuestion,ChooseThreeQuestion, CheckQuestion,ReadingTest, Score,ExamScore,ScoreTable,CategoryQuestion,FillQuestion,OE,Audio
from exam.models import ListeningTest,ListeningTopic,ListeningCheckQuestion,ListeningChooseQuestion,ListeningChooseTwoQuestion,ListeningMatchQueston,ListeningPreListening
@login_required
def listen(request):
    # note that MP3_STORAGE should not be in MEDIA_ROOT
	
    return render_to_response("exam/passages.html", {
		}, context_instance=RequestContext(request))

def home(request):
	aa = Audio.objects.all()
	a = aa[0]
	
	return render_to_response("exam/listening_first.html", {
	"home":request.get_host(),
	"link":str(a.audio)	
		}, context_instance=RequestContext(request))
#Shalgaltuudiig haruulah
@login_required
def exams(request):	
		tests = ReadingTest.objects.all()
		ltests = ListeningTest.objects.all()
		return render_to_response("exam/passages.html", {
			"tests":tests,
			"ltests":ltests,
			"home":request.get_host(),
			
		}, context_instance=RequestContext(request))
#Zaavar oruulah

@login_required
def instruction(request,test_id):
		
		return render_to_response("exam/first.html", {
			"exam_id":test_id,
			"home":request.get_host(),
					
		}, context_instance=RequestContext(request))
#Listening Intstruction
@login_required
def instruction_l(request,test_id):
		
		return render_to_response("exam/first.html", {
			"exam_id":test_id,
			"home":request.get_host(),
					
		}, context_instance=RequestContext(request))
		
def exam(request,test_id):
		
		passage, a1,test,exam_id,cat,cat2,cat1= data(test_id,0)
		print  str(request.user.id) + "  USER ID"
		return render_to_response("exam/test.html", {
			"test":test,
			"cat":cat,"cat1":cat1,"cat2":cat2,
			"body":passage,
			"tests":a1,
			"count": len(a1),
			"test_id": test_id,
			"time": 1200,
			"pass_c":1,	
			"exam_id":exam_id,		
		}, context_instance=RequestContext(request))

def exam1(request,examScore_id):
		s1 = ExamScore.objects.get(id=examScore_id);
		print "examScore "  + str(examScore_id)
		test_id = s1.test_id;
		passage_index = s1.passage_index; 
		timeRemain = s1.time_left;
		print 'Passage index  '+ str(passage_index)
		
		if passage_index==3:
			s1 = ExamScore.objects.filter(user_id=1,test_id=test_id)
			score = s1[0].score + s1[1].score + s1[2].score
			
			toefl = getToeflScore(test_id,score)
			ExamScore.objects.filter(user_id=1,test_id=test_id).delete()
			
			print request.user.id
			sd = Score(user_id = request.user.id,test_id = test_id, score = toefl)
			sd.save()
			return redirect('/exam/score/' + str(sd.id))
		else:
			passage, a1,test,exam_id,cat,cat2,cat1 = data(test_id,passage_index)
			return render_to_response("exam/test.html", {
					"test":test,
					"body":passage,"cat":cat,"cat1":cat1,"cat2":cat2,
					"tests":a1,
					"count": len(a1),
					"test_id": test_id,
					"time": 1200,
					"pass_c":passage_index+1,	
						
				}, context_instance=RequestContext(request))

@login_required
def ex(request,score_id):	
		score = Score.objects.get(id=score_id)
		sc = score.score
		return render_to_response("exam/score.html", {
			"point":sc,
			
		}, context_instance=RequestContext(request))

@login_required
def xhr_test(request):
		if request.is_ajax():
		    if request.method == 'GET':
		        message = "This is an XHR GET request"
		    elif request.method == 'POST':				
		        message = str(request.POST)		       
		else:
		    message = "No XHR"		
		sheet,total = checkk(request) 
		
		return HttpResponse(sheet, total)
			
@login_required
def finish(request):
		if request.method == 'POST':
			
			sheet,total,timeRemain,test_id,pass_c ,exam_id= checkk(request) 
		
		s1 = ExamScore(user_id=request.user.id,test_id = test_id,passage_id =exam_id,passage_index=pass_c,score=total,time_left=timeRemain);
		s1.save();
		print str(s1.id) + "Exam Score ID"
		
		return HttpResponse(s1.id)
@login_required
def fin(request):
		if request.method == 'POST':
			
			sheet,total,timeRemain,test_id,pass_c ,exam_id= checkk(request) 
			
		s1 = ExamScore(user_id=1,test_id = test_id,passage_id =exam_id,passage_index=pass_c,score=total,time_left=timeRemain);
		s1.save();
		timeRemain = int(timeRemain)
		pass_c = int(pass_c)
		if timeRemain==0:
			print 'time remain is over and Passage is : ' + str(pass_c) + " time is " + str(timeRemain)
			if pass_c==1 or pass_c==0:
				d = ExamScore.objects.filter(user_id=request.user.id , test_id=test_id)
				print sc +' score  test id  '+ test_id
				sc = d[0].score 
				
 				toefl = getToeflScore(test_id,sc)
				ExamScore.objects.filter(user_id=request.user.id , test_id=test_id).delete()
				d = Score(user_id=request.user.id,test_id=test_id,score=toefl)
				d.save()
				d.id
				return HttpResponse(d.id)	
			if pass_c==2:
				print 'c=2'
				d = ExamScore.objects.filter(user_id=request.user.id , test_id=test_id)
				sc = d[0].score + d[1].score
				toefl = getToeflScore(test_id,sc)
				ExamScore.objects.filter(user_id=request.user.id, test_id=test_id).delete()
				d = Score(user_id=request.user.id,test_id=test_id,score=toefl)
				d.save()
				d.id
				return HttpResponse(d.id)
			if pass_c==3:
				print 'c=3'
				d = ExamScore.objects.filter(user_id=request.user.id,test_id=test_id)
				sc = d[0].score + d[1].score + d[2].score
				toefl = getToeflScore(test_id,sc)
				ExamScore.objects.filter(user_id=request.user.id,test_id=test_id).delete()
				d = Score(user_id=request.user.id,test_id=test_id,score=toefl)
				d.save()
				d.id
				return HttpResponse(d.id)	
		else:

			return HttpResponse(s1.id)
			
def check_two(c1,c2,u1,u2):
	value = 0
	if c1==u1 or c1==u2:
		value = value + 1
	if c2==u1 or c2==u2:
		value = value +1
	return value

def check_three(c1,c2,c3,u1,u2,u3):
	value = 0
	if c1==u1 or c1==u2 or c1==u3:
		value = value + 1
	if c2==u1 or c2==u2 or c2==u3:
		value = value +1
	if c3==u1 or c3==u2 or c3==u3:
		value = value +1
	return value
	
def hehe(request):
	tests = Passage.objects.all()
	return render_to_response("exam/score.html", {
		"tests":tests,	
	}, context_instance=RequestContext(request))

def checkk(request):
	types = request.POST.getlist('types')
	answer1 = request.POST.getlist('answer1')
	answer2 = request.POST.getlist('answer2')
	answer3 = request.POST.getlist('answer3')
	ids = request.POST.getlist("ids")

	sheet = answer1
	test_id=request.POST.getlist("test_id")
	test_id = test_id[0]
	print test_id
	pass_c=request.POST.getlist("pass_c")
	pass_c = pass_c[0]
	timeRemain = request.POST.getlist("time")
	timeRemain = timeRemain[0]
	
	exam_id = request.POST.getlist("exam_id")		
	exam_id =exam_id[0]
	catIs = request.POST.getlist("cat_q")
	catIs = str(catIs[0])
	if 'true' in catIs:
		p_id = request.POST.getlist("p_id")
		p_id = p_id[0]
		tA =0
		catScore = 0;		
		cq = CategoryQuestion.objects.get(passage=p_id)
		
		cA = set([cq.c1a1,cq.c1a2,cq.c1a3,cq.c1a4])
		
		if 0 in cA:
			cA.remove(0)
		catAnsA = request.POST.getlist("cat_ansA")
		
		catAnsA = catAnsA[0]
		sub = len(catAnsA.replace('c','').replace('.','').split())-len(cA)
		if sub>0:
			tA = tA-sub
		
		catAnsA = catAnsA.replace('c','').replace('.','').split()
		
		for i in range(len(catAnsA)):
			catAnsA[i] = int(catAnsA[i])
		
		for i in range(len(catAnsA)):
			if catAnsA[i] in cA:
				tA=tA+1
				
		print "category A score "  + str(tA)
		
		cB = set([cq.c2a1,cq.c2a2,cq.c2a3,cq.c2a4])
		
		if 0 in cB:
			cB.remove(0)
			
		if len(cB)>0:
			tB = 0
			catAnsB = request.POST.getlist("cat_ansB")
			catAnsB = catAnsB[0]
			sub = len(catAnsB.replace('c','').replace('.','').split())-len(cB)
			if sub>0:
				tB = tB-sub
			catAnsB = catAnsB.replace('c','').replace('.','').split()
			for i in range(len(catAnsB)):
				catAnsB[i] = int(catAnsB[i])
			for i in range(len(catAnsB)):
				if catAnsB[i] in cB:
					tB=tB+1
			tC = tA+tB
			if tC>=7:
				catScore = 4
			elif tC>=5:
				catScore =3
			elif tC>=3:
				catScore =2;
			elif tC>=1:
				catScore =1;
		else:
			catScore = tA
		print "Category Question answer " + str(catScore)		
				
	for i in range(len(types)):
		types[i]=int(types[i])
		answer1[i]=int(answer1[i])
		answer2[i]=int(answer2[i])
		answer3[i]=int(answer3[i])
		ids[i] = int(ids[i])
		sheet[i] = int(sheet[i])		
	for i in range(len(types)):
		if types[i]==1:
			correct = int(ChooseQuestion.objects.get(id=ids[i]).correct);				
			user_answer = answer1[i]
			if user_answer == correct:
				sheet[i] = 1;
			elif user_answer==-1:
				sheet[i] = -1
			else:
				sheet[i]=0
		elif types[i]==2:
			c1 = int(ChooseTwoQuestion.objects.get(id=ids[i]).correct1)
			c2 = int(ChooseTwoQuestion.objects.get(id=ids[i]).correct2)
			u1 = answer1[i];
			u2 = answer2[i]
			sheet[i] = check_two(c1,c2,u1,u2)
		elif types[i]==3:
			c1 = int(ChooseThreeQuestion.objects.get(id=ids[i]).correct1)
			c2 = int(ChooseThreeQuestion.objects.get(id=ids[i]).correct2)
			c3 = int(ChooseThreeQuestion.objects.get(id=ids[i]).correct3)
			u1 = answer1[i];
			u2 = answer2[i]
			u3 = answer3[i]
			sheet[i] = check_three(c1,c2,c3,u1,u2,u3)
		elif types[i] == 5:
			print  "5555555555 ANSWER SENT TO SERVER" 
		elif types[i] == 6:
			print "FILL ID " + str(ids[i])
			c1 = int(FillQuestion.objects.get(id=ids[i]).answer)
			print "Correct " +str(c1)
			print "YOUR " + str(answer1[i])
			if c1==int(answer1[i]):
				print "CONGRATULATIONS FILL ANSWER IS CORRECT"
				sheet[i] = 1;
			else:
				print "FILL ANSWER IS INCORRECT"  
	total = 0		
	for i in range(len(sheet)):
		
		if sheet[i]==-1:
			sadsad = 45; 
		else:
			total = total+sheet[i]
	print total
	return sheet, total, timeRemain,test_id,pass_c,exam_id

def data(test_id,index):
		print "data function  index " + str(index)
		ss = Passage.objects.filter(test=test_id).order_by("id")
		test = ss[index]
		exam_id = ss[index].id
	
		q1 = ChooseQuestion.objects.filter(passage=exam_id)
		q2 = ChooseTwoQuestion.objects.filter(passage=exam_id)
		q3 = ChooseThreeQuestion.objects.filter(passage=exam_id)
		q4 = CheckQuestion.objects.filter(passage=exam_id)
		q5 = CategoryQuestion.objects.filter(passage=exam_id)
		q6 = FillQuestion.objects.filter(passage=exam_id)
		
		
		cat =0;
		cat1 = ''
		cat2 =''
		catAns =False
		
		a1 = []
		for i in range(0,len(q1)):
			t = ChooseQuestion()
			t.id = q1[i].id
			t.type = q1[i].type
			t.index =len(q1)-i
			t.passage = q1[i].passage	
			t.question = q1[i].question 
			t.answer1=q1[i].answer1
			t.answer2=q1[i].answer2
			t.answer3=q1[i].answer3
			t.answer4=q1[i].answer4
			t.correct=q1[i].correct
			a1.append(t)
			
		dd = (len(a1))
		a2 = []
		for i in range(0,len(q2)):
			t = ChooseTwoQuestion()
			t.id = q2[i].id
			t.type = q2[i].type
			t.index =dd+(len(q2)-i)
			t.passage = q2[i].passage	
			t.question = q2[i].question 
			t.answer1=q2[i].answer1
			t.answer2=q2[i].answer2
			t.answer3=q2[i].answer3
			t.answer4=q2[i].answer4
			t.correct1=q2[i].correct1
			t.correct2=q2[i].correct2
			a1.append(t)
		dd = (len(a1))
		for i in range(0,len(q3)):
			t = ChooseThreeQuestion()
			t.id = q3[i].id
			t.type = q3[i].type
			t.index =dd+(len(q3)-i)
			t.passage = q3[i].passage	
			t.question = q3[i].question 
			t.answer1=q3[i].answer1
			t.answer2=q3[i].answer2
			t.answer3=q3[i].answer3
			t.answer4=q3[i].answer4
			t.answer5=q3[i].answer5
			t.answer6=q3[i].answer6
			t.answer7=q3[i].answer7
			t.answer8=q3[i].answer8
			t.answer9=q3[i].answer9
			t.answer10=q3[i].answer10
			t.correct1=q3[i].correct1
			t.correct2=q3[i].correct2
			t.correct3=q3[i].correct3
			a1.append(t)
		dd= len(a1)
		for i in range(0,len(q4)):
			t = CheckQuestion()
			t.type = 4
			t.id = q4[i].id
			t.index =dd+(len(q4)-i)
			t.passage = q4[i].passage
			t.question =q4[i].question 
			t.answer1 =q4[i].answer1
			t.correct1 =q4[i].correct1
			t.answer2 =q4[i].answer2
			t.correct2 = q4[i].correct2
			t.answer3 = q4[i].answer3
			t.correct3 = q4[i].correct3
			t.answer4 =q4[i].answer4
			t.correct4 =q4[i].correct4
			t.answer5 =q4[i].answer5 
			t.correct5 =q4[i].correct5 
			t.answer6 =q4[i].answer6
			t.correct6 =q4[i].correct6
			t.answer7 =q4[i].answer7
			t.correct7 = q4[i].correct7 
			t.answer8 = q4[i].answer8 
			t.correct8 =q4[i].correct8 
			a1.append(t)
		dd=len(a1)	
		for i in range(0,len(q5)):
			catAns = True;
			t = CategoryQuestion()
			t.type = 5
			t.id = q5[i].id
			t.index=dd+(len(q5)-i)
			t.passage = q5[i].passage
			t.question = q5[i].question
			t.choice1 = q5[i].choice1
			t.choice2 = q5[i].choice2
			t.choice3 = q5[i].choice3
			t.choice4 = q5[i].choice4
			t.choice5 = q5[i].choice5
			t.choice6 = q5[i].choice6
			t.choice7 = q5[i].choice7
			t.choice8 = q5[i].choice8
			t.choice9 = q5[i].choice9
			t.choice10 = q5[i].choice10
			t.category1 = q5[i].category1
			cat1 = t.category1
			t.c1a1 = q5[i].c1a1
			t.c1a2 = q5[i].c1a2
			t.c1a3 = q5[i].c1a3
			t.category2 = q5[i].category2
			if t.category2 == '':
				cat = 1
			else:
				cat2=t.category2
				cat = 2 
			t.c2a1 = q5[i].c2a1
			t.c2a2 = q5[i].c2a2
			t.c2a3 = q5[i].c2a3
			a1.append(t)
		dd= len(a1)
		if len(q6)==0:
			print "Fill question has not"
		else:
			for i in range(0,len(q5)):
				t = FillQuestion()
				t.type = 6
				t.id = q6[i].id
				
				t.index =dd+(len(q6)-i)
				t.passage = q6[i].passage
				t.question =q6[i].question 
				t.sectionA =q6[i].sectionA
				t.sectionB =q6[i].sectionB
				t.sectionC =q6[i].sectionC
				t.sectionD =q6[i].sectionD
				
				a1.append(t)
			dd= len(a1)
		passage = test.body.raw
		
		return passage, a1,test,exam_id,cat,cat2,cat1
def getToeflScore(test_id, raw_score):
	toefl = ScoreTable.objects.get(test_id=test_id,raw=raw_score).toefl
	return toefl

